package com.tensquare.base.service;

import com.tensquare.base.dao.LabelDao;
import com.tensquare.base.pojo.Label;
import com.tensquare.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;

/**
 * 业务层代码
 */
@Service
public class LabelService {

    @Autowired
    private LabelDao labelDao;

    @Autowired
    private IdWorker idWorker;

    /**
     * 查询所有
     * @return
     */
    public List<Label> findAll(){
        return labelDao.findAll();
    }

    /**
     * 根据id查询一个
     * @param id
     * @return
     */
    public Label findById(String id){
        int i = new Random().nextInt(1000);
        if(i<500){
            throw  new RuntimeException("抛一个异常！！！！"+i);
        }
        return labelDao.findById(id).get();
    }

    /**
     * 新增
     * @param label
     */
    @Transactional
    public void add(Label label){
        label.setId(idWorker.nextId()+"");//加入主键
        labelDao.save(label);
    }

    /**
     * 修改
     * @param label
     */
    @Transactional
    public void update(Label label){
        labelDao.save(label);
    }

    /**
     * 删除
     * @param id
     */
    @Transactional
    public void deleteById(String id){
        labelDao.deleteById(id);
    }
}
